using DG.Tweening;
using TMPro;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Networking;
using System.Collections;

public class LoginUI : MonoBehaviour
{
    public TMP_InputField usernameInput;
    public TMP_InputField passwordInput;
    public Button loginButton;
    public TextMeshProUGUI messageText;

    private void Start()
    {
        messageText.text = "";
        loginButton.onClick.AddListener(OnLoginClick);
    }

    public void OnLoginClick()
    {
        loginButton.transform.DOScale(0.9f, 0.1f).OnComplete(() =>
        {
            loginButton.transform.DOScale(1f, 0.1f);
        });

        string user = usernameInput.text.Trim();
        string pass = passwordInput.text;

        user = "gamer01";
        pass = "123";

        if (string.IsNullOrEmpty(user) || string.IsNullOrEmpty(pass))
        {
            ShowMessage("请输入用户名和密码");
            return;
        }

        StartCoroutine(LoginUser(user, pass));
    }

    private IEnumerator LoginUser(string userid, string psw)
    {
        ShowMessage("登录中...", Color.yellow);

        string url = $"http://192.168.3.109:9300/zone/getZone?channel=dev&system=0&userid={userid}&appverison=1.0.0&psw={psw}&type=2";
        
        using (UnityWebRequest request = UnityWebRequest.Get(url))
        {
            yield return request.SendWebRequest();

            if (request.result != UnityWebRequest.Result.Success)
            {
                ShowMessage("网络错误: " + request.error);
            }
            else
            {
                string response = request.downloadHandler.text;
                Debug.Log("登录响应: " + response);

                // 简单解析JSON响应
                if (response.Contains("\"code\":0"))
                {
                    ShowMessage("登录成功!", Color.green);
                }
                else if (response.Contains("\"code\":250"))
                {
                    ShowMessage("登录失败，无效的凭据");
                }
                else
                {
                    ShowMessage("登录失败，未知错误");
                }
            }
        }
    }

    private void ShowMessage(string msg, Color? color = null)
    {
        messageText.text = msg;
        messageText.color = color ?? Color.red;
        //messageText.DOFade(0f, 0f);
        //messageText.DOFade(1f, 0.3f);
    }
}
